var rewire = require("rewire")
const redis = require("redis")


let client = null


async function getClient() {
  if (!client) {
    client = redis.createClient(6379, '127.0.0.1')
    await client.connect()
  }
  return client
}


async function getCache(key) {
  const client = await getClient()
  const valRs = await client.get(key)
  return backSpecial(JSON.parse(valRs))
}

async function saveCache(key, val, sec = 3600 * 24) {
  const client = await getClient()
  await client.set(key, JSON.stringify(convertSpecial(val)))
  await client.expire(key, sec)
}

async function existsCache(key) {
  const client = await getClient()
  return await client.exists(key)
}

function backSpecial(rs) {
  if (rs === '<null>') {
    return null
  }
  else if (rs === '<false>') {
    return false
  }
  else {
    return rs
  }
}

function convertSpecial(rs) {
  if (rs === null || typeof(rs) === 'undefined') {
    return '<null>'
  }
  else if (rs === false) {
    return '<false>'
  }
  else {
    return rs
  }
}

module.exports = {getClient, getCache, saveCache, existsCache}
